package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.project.bean.OrderBean;
import com.project.bean.ShopBean;
import com.project.bean.UserBean;
import com.project.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderController {
    @Autowired
    private IOrderService service;

    @RequestMapping("submit")
    public String submitOrder(@Valid OrderBean order, BindingResult result, HttpServletRequest request)
            throws Exception {
        if(result.hasErrors()){
            return new ObjectMapper().writeValueAsString(result.getFieldErrors());
        }

        UserBean user = (UserBean) request.getSession().getAttribute("loginUser");
        Map<Integer, ShopBean> map = (Map<Integer,ShopBean>)request.getSession().getAttribute("shopMap");
        order.setUser(user);
        service.add(order,map);
        map.clear();
        return "ok";
    }

    @RequestMapping("findAllByUserId")
    public PageInfo<OrderBean> findAllByUserId(int pageNO, int userId, HttpServletRequest request){
        return service.findAllByUserId(pageNO,userId);
    }

    @RequestMapping("findById")
    public OrderBean findById(int id){
        return service.findById(id);
    }

    @RequestMapping("findAllByItem")
    public PageInfo<OrderBean> findAllByItem(int pageNO, String status, LocalDate startDate, LocalDate endDate){
        return service.findAllByItem(pageNO,status,startDate,endDate);
    }

    @RequestMapping("sending")
    @ResponseBody
    public String sending(int id, String str){
        service.updateState(id,str);
        return "ok";
    }

}
